<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="crud.toDetail('financeCustomerReceiptDetail')"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="exportDetail('\\exportBankDetail')"
        >
          导出银行详情
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="exportDetail('\\exportOrderDetail')"
        >
          导出单据详情
        </el-button>
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="primary"-->
        <!--        >-->
        <!--          打印-->
        <!--        </el-button>-->
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="primary"-->
        <!--        >-->
        <!--          打印预览-->
        <!--        </el-button>-->

        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          @click="getMergeList"
        >
          收款单合并
        </el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
        >打印</el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
        >打印预览</el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-notebook-2"
          :disabled="crud.selections.length < 1"
          @click="tabInvoiceType('receiptCollectPrint',0)"
        >收款单汇总打印</el-button>

        <el-button
          class="filter-item"
          size="mini"
          slot="left"
          type="warning"
          v-permission="permission.onlineRechargeQuery"
          @click="lineRechargeQuery"
        >线上充值查询</el-button>
      </crudOperation>
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="100px" v-formkey="{query:crud.toQuery}">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单据编号">
                <el-input v-model="query.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称">
                <zSelect :value.sync="query.customerId" url="api/dropDown/basCustomerList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="query.orderStatus" class="filter-item" clearable placeholder="状态"
                           size="small" style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="收款类型">
                <el-select v-model="query.type" class="filter-item" clearable placeholder="状态" size="small"
                           style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.t_finance_customer_receipt_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行账号">
                <zSelect :value.sync="query.bankId" url="api/dropDown/basBankList"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售单号">
                <el-input v-model="query.salesOrderCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="来源单据编号">
                <el-input v-model="query.sourceCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="来源单据类型">
                <el-select v-model="query.sourceType" class="filter-item" clearable placeholder="来源单据类型" size="small" style="width: 100%;">
                  <el-option  v-for="item in dict.t_finance_customer_receipt_source_type"
                              :key="item.id"
                              :label="item.label"
                              :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="query.remark"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="回箱单号">
                <el-input v-model="query.returnBoxOrderCode"></el-input>
              </el-form-item>
            </el-col>


          </el-row>
          <el-row gutter="10">
            <el-col :span="6">
              <el-form-item label="人员">
                <zSelect :value.sync="userIds" multiple url="/api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款人">
                <zSelect :value.sync="payeeUserIds" multiple url="/api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出纳">
                <zSelect :value.sync="cashierUserIds" multiple url="/api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商贸公司">
                <zSelect multiple :value.sync="query.fCustomerIds"  url="api/dropDown/basCustomerList" :params="{type:2}"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二批">
                <zSelect multiple :value.sync="query.sCustomerIds"  url="api/dropDown/basCustomerList" :params="{type:3}"
                         style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="6" content="">
              <el-button class="filter-item"  size="mini" type="primary" @click="queryReport">搜索</el-button>
              <el-button class="filter-item" plain   size="mini" type="primary"
                         @click="resetQuery" >重置</el-button>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <!--表格渲染-->
      <div  class="table-container" >
        <el-table ref="table"
                  border v-loading="crud.loading" :data="crud.data" :height=tableHeight size="small" style="width: 100%;"
                  :summary-method="sumRow"
                  show-summary
                  height="700"
                  @row-click="crud.selectRow"
                  v-draghead="manyTableOption"
                  @header-dragend="changeColWidth"
                  :row-style="crud.rowClass"
                  :row-class-name="crud.tableRowClassName"
                  @selection-change="crud.selectionChangeHandler"
                  @row-dblclick="crud.toDetailPlus('financeCustomerReceiptDetail',$event.id)"
        >
          <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
          <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
          <el-table-column v-if="item.visible" v-for="(item, index) in header" :key="item.prop+index" :prop="item.prop" :label="columnLabel(item)" :width="item.width + 'px'"  ><template slot-scope='{row,$index}'><span v-if='item.type == 1'>{{ row[`${item.prop}`] }}</span><span v-else-if='item.type == 2' >{{ parseTime(row[`${item.prop}`])}}</span><span v-else-if='item.type == 3' >{{ getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`) }}</span><span v-else-if="item.type == 4"><span v-if="item.prop == 'type'"> {{ row.type|typeFilter(dict.t_finance_customer_receipt_type) }} </span><span v-if="item.prop == 'sourceType'"> <span v-for="item in dict.t_finance_customer_receipt_source_type" v-if="item.value == row.sourceType">{{ item.label }}</span> </span><span v-if="item.prop == 'orderStatus'"> {{ row.orderStatus|orderStatusFilter(dict.common_order_status) }} </span></span> </template> </el-table-column> <el-table-column :render-header="crud.renderHeader" v-permission="['admin','edit','delte']" label="操作" width="150px" align="center" > <template slot-scope="scope"> <udOperation :data="scope.row" :permission="permission"/> </template> </el-table-column>
        </el-table>
      </div>
      <!--分页组件-->
      <pagination/>
    </div>
    <el-dialog title="表格配置"
               :visible.sync="tableConfigShow"
               width="60%">
      <j-table-column-config :columns.sync="header"  @tabSave="saveHead"/>
    </el-dialog>
    <right-click-menu @tableConfig="tableConfig" :options.sync="rightClickMenuConfig" />
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="financeCustomerReceipt"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.toPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="financeCustomerReceipt"
                    v-if="pringDialog"
                    @getPrintId="print"
      ></jPrintConfig>
    </el-dialog>
    <j-dialog
      title="合并收款单"
      :visible.sync="showMerge"
      is-mask
    >
      <div>
        <el-table
          :data="mergeData"
          border
          height="500"
          style="width: 100%">
          <el-table-column label="选择" width="60">
            <template slot-scope="scope">
              <el-radio v-model="mergeRadio" :label="scope.$index">&nbsp</el-radio>
            </template>
          </el-table-column>
          <el-table-column  type="index" width="60" label="序号"/>
          <el-table-column
            prop="code"
            label="收款单编号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="taxAmount"
            label="收款金额"
            width="180">
          </el-table-column>
          <el-table-column
            prop="cancelAmount"
            label="已核销金额"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            width="180"
          >
          </el-table-column>
        </el-table>
      </div>
      <div class="flex flex-reverse">
        <el-button type="primary" @click="submitMgerge">提交</el-button>
      </div>
    </j-dialog>
  </div>
</template>

<script>
import crudFinanceCustomerReceipt from '@/api/erp/financeCustomerReceipt';
import CRUD, {crud, header, presenter} from '@crud/crud';
import rrOperation from '@crud/RR.operation';
import crudOperation from '@crud/CRUD.operation';
import udOperation from '@crud/UD.operation';
import pagination from '@crud/Pagination';
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import {download} from '@/api/data'
import {downloadFile,} from '@/utils/index'
import jDialog from '@/components/jDialog/jDialog'
import qs from 'qs'

import{manyTableMixin}from"../../../mixins/manyTableMixin";
import { onlineRechargeQuery } from '../../../api/erp/financeCustomerReceipt'

// crud交由presenter持
const defaultCrud = CRUD({
  optShow: {
    add: false,
    edit: false,
    del: true,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false,
    pass: true,
    reject: true,
    print: true,
    printDetail: true,
    downloadDetail: false,
    invalid:true,
  },
  title: '收款单',
  url: 'api/financeCustomerReceipt',
  sort: 'id,desc',
  crudMethod: {...crudFinanceCustomerReceipt}
});

export default {
  name: 'financeCustomerReceipt',
  components: {pagination, crudOperation, rrOperation, udOperation, jPrintConfig, jDialog},
  dicts: ['common_order_status', 't_finance_customer_receipt_type', 't_finance_customer_receipt_source_type'],
  mixins: [presenter(defaultCrud), header(), crud(),manyTableMixin],
  data() {
    return {
      // bigHeight:'',
      tableHeight:'',
      showMerge: false,
      mergeRadio:null,
      mergeData: [],
      userIds: [],
      payeeUserIds: [],
      cashierUserIds: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dataExtent: [],
      permission: {
        add: ['admin', 'financeCustomerReceipt:add'],
        edit: ['admin', 'financeCustomerReceipt:edit'],
        del: ['admin', 'financeCustomerReceipt:del'],
        import: ['admin', 'financeCustomerReceipt:import'],
        export: ['admin', 'financeCustomerReceipt:export'],
        copy: ['admin', 'financeCustomerReceipt:copy'],
        upload: ['admin', 'financeCustomerReceipt:upload'],
        download: ['admin', 'financeCustomerReceipt:download'],
        pass: ['admin', 'financeCustomerReceipt:pass'],
        reject: ['admin', 'financeCustomerReceipt:reject'],
        closed: ['admin', 'financeCustomerReceipt:closed'],
        invalid: ['admin', 'financeCustomerReceipt:invalid'],
        stop: ['admin', 'financeCustomerReceipt:stop'],
        recover: ['admin', 'financeCustomerReceipt:recover'],
        onlineRechargeQuery: ['admin', 'financeCustomerReceipt:onlineRechargeQuery']
      },
      rules: {},
      pringDialog: false,
      isPreview:0,
      printIds:[],
      invoiceType: "receiptCollectPrint"
    };
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  created() {
    this.setTableHeight()
  },

  mounted() {
    window.onresize = () => {
      return (() => {
        this.setTableHeight()
      })();
    };
  },

  filters: {
    typeFilter(val, list) {
      const item = list.find(el => el.value === val);
      if (item) {
        return item.label;
      } else {
        return '-';
      }
    },
    orderStatusFilter(val, list) {
      const item = list.find(el => el.value === val);
      if (item) {
        return item.label;
      } else {
        return '-';
      }
    }
  },
  watch: {

  },

  methods: {
    queryReport(){
      this.query.userIds = this.userIds.length?this.userIds.join(','):''
      this.query.payeeUserIds = this.payeeUserIds.length?this.payeeUserIds.join(','):''
      this.query.cashierUserIds = this.cashierUserIds.length?this.cashierUserIds.join(','):''
      this.crud.toQuery()
    },
    resetQuery(){
      this.userIds = []
      this.payeeUserIds = []
      this.cashierUserIds = []
      this.crud.resetQuery()
    },
    tabInvoiceType(val,isPreview){
      this.invoiceType = val
      this.preView(isPreview)
    },
    preView(val){
      this.isPreview = val
      this.pringDialog = true
    },
    print(val){
      if(val !== null){
        this.pringDialog=false
        localStorage.setItem(this.invoiceType,val)
        console.log('设置打印缓存成功')
        this.crud.doPrint(val,this.printIds,this.isPreview,this.invoiceType)
      }else {
        this.$message.error('请选择打印模板');
      }
    },
    // onresize(e){
    //
    //   console.log(e)
    //   console.log(window.devicePixelRatio)
    //   const app = document.getElementsByClassName('crud-opts')[0]
    //   let screenHeight = document.documentElement.clientHeight  ;
    //   this.Height = screenHeight-app.offsetTop-12;
    //   console.log('========')
    //   console.log(app.offsetTop)
    //   console.log(this.Height)
    // },
    setTableHeight(){
      const ratio =this.getRatio() / 100
      this.tableHeight = (window.screen.height - (200*ratio)) / ratio
    },
    lineRechargeQuery(){
      const ids = this.crud.selections.filter(item=>item.type === 2 && item.payType).map(item=>item.id).join(',')
      ids.length
      &&
      onlineRechargeQuery({orderIds:ids}).then(res=>{
        this.crud.refresh()
      })
    },
    getRatio() {
      var ratio = 0;
      var screen = window.screen;
      var ua = navigator.userAgent.toLowerCase();

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }

      } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
      }

      if (ratio) {
        ratio = Math.round(ratio * 100);
      }
      return ratio;
    },
    async getMergeList(){
      const ids = this.crud.selections.map(item=>item.id).join(',')
     const res = await crudFinanceCustomerReceipt.getMergeData({ids:ids})
      if (res.status === 200){
        this.mergeData = res.data.content
        this.showMerge = true
      }
    },
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    setMergeBill(select,row){
      console.log(select)
    },
    async submitMgerge(){
      const ids = this.mergeData.map(item=>item.id).join(',')
      const mergeId = this.mergeData[this.mergeRadio].id
      const data = await crudFinanceCustomerReceipt.merge({ids,mergeId})
      if(data.status === 200){
        this.showMerge = false
        this.$message.success(data.msg)
        this.mergeData = null
        this.mergeRadio = null
        this.crud.refresh()
      }else {
        this.$message.error(data.msg)
      }
    },
    exportDetail(type) {
      this.crud.downloadDetailLoading = true
      this.crud.query.orderIds = ''
      this.crud.query.ids = ''
      this.crud.selections.forEach(item => {
        this.crud.query.orderIds += item.id + ','
      })
      const params = this.crud.getQueryParams()
      download(this.crud.url + type, params).then(result => {
        downloadFile(result, this.crud.title + '数据', 'xlsx')
        this.crud.downloadDetailLoading = false
      }).catch(() => {
        this.crud.downloadDetailLoading = false
      })
    },
    getValue(e) {
      this.query.startTime = this.dataExtent[0];
      this.query.endTime = this.dataExtent[1];
    },
    sumRow({columns, data}) {
      const sums = []
      for (let i in columns) {
        sums[i] = this.crud.summary[columns[i].property] || ''
      }
      sums[0] = '合计'
      return sums
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if ([4, 5, 11].includes(index)) {
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += '';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    }
  }
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
